package com.wan37.logic.email.dao.impl;

import com.wan37.logic.email.dao.EmailDao;
import com.wan37.logic.email.domain.entity.EmailDO;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author : luoyong
 * @date : 2020-07-28 10:38
 **/
@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)
@Repository
public class EmailDaoImpl implements EmailDao {
    @Autowired
    private HibernateTemplate hibernateTemplate;
    @Override
    public boolean add(EmailDO emailDO) {
        try{
            hibernateTemplate.save(emailDO);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean delete(Integer id) {
        try{
            hibernateTemplate.delete(id);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(EmailDO emailDO) {
        try {
            Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
            Query query = session.createQuery("update EmailDO set isRead = ? where emailId=? and receiverId = ?");
            query.setParameter(0, emailDO.getIsRead());
            query.setParameter(1, emailDO.getEmailId());
            query.setParameter(2, emailDO.getReceiverId());
            query.executeUpdate();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<EmailDO> getAll() {
        return (List<EmailDO>) hibernateTemplate.find("from EmailDO");
    }

    @Override
    public List<EmailDO> getEmailDOAndReceiverId(String userId) {
        return (List<EmailDO>) hibernateTemplate.find("from EmailDO where receiverId = ?", userId);
    }
}
